/**
 * 
 */
package com.worksmap.core.service.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.worksmap.core.constant.ConstantUtil;
import com.worksmap.core.constant.LoginConstant;
import com.worksmap.core.constant.RateConstant;
import com.worksmap.core.dao.BaseDao;
import com.worksmap.core.entity.TaoBaoSeller;
import com.worksmap.core.entity.User;
import com.worksmap.core.service.CookieService;
import com.worksmap.core.service.LoginService;
import com.worksmap.core.service.UserService;
import com.worksmap.core.util.CookieUtil;
import com.worksmap.core.util.StringUtil;
import com.worksmap.core.util.encrypt.MD5;

/**
 * @author jack
 * 2013.7.25
 */
@Service
public class LoginServiceImpl implements LoginService {
	
	private final Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	private BaseDao baseDao;
	@Autowired
	private UserService userService;
	@Autowired
	CookieService cookieService;
	
	static String addUser = "insert into user(username,password,first_name,last_name,birthday,age) values(:userName,:passWord,:firstName,:lastName,:birthday,:age);";
	static String getUser = "select * from user where userName = ? and passWord = ?";
	
	@Override
	public User getUser(String userName, String password) {
		User user = baseDao.getObject(getUser, User.class, new Object[]{userName,password});
		return user;
	}
	
	private User getUsertest(String userName, String password) {
		String sql = "select * from user where userName = ?";
		User user = baseDao.getObject(sql, User.class, new Object[]{userName});
		return user;
	}

	@Override
	public boolean isUserLogined(HttpServletRequest request) {
		return false;
	}

	@Override
	public User getCurrentUser(HttpServletRequest request) {
		return null;
	}

	@Override
	public boolean isAdminLogined(HttpServletRequest request) {
		return false;
	}

	@Override
	public User getCurrentAdmin(HttpServletRequest request) {
		return null;
	}

	public int userLogin(String userName, String userPass,
			HttpServletRequest request, HttpServletResponse response){
		User user = null;
		if(StringUtil.isNotBlank(userName)){
			try {
				user = userService.getUserByUserName(userName);
			} catch (Exception e) {
				logger.error("���username��ȡ�û��쳣" + e);
				return LoginConstant.LOGIN_FAILED;
			}
		}
		if(user == null){
			return LoginConstant.LOGIN_FAILED_USER_NOT_EXIST;
		}
		if(StringUtil.isNotBlank(userPass) && !MD5.encodePassword(userPass, "MD5").equalsIgnoreCase(user.getPassWord())){
			return LoginConstant.LOGIN_FAILED_PASS_ERROR;
		}
		//��Ȩ
		String sessionId = getSessionIdForUser(user);
		try {
			CookieUtil.setPageCookie(response, ConstantUtil.SESSION_ID_NAME, sessionId, 
					 "jack");
			CookieUtil.setPageCookie(response, ConstantUtil.USER_SESSION_ID_NAME, 
					String.valueOf(user.getId()), "jack");
		} catch (Exception e) {
			logger.error("�����û���½���cookieʧ�ܣ�" + e);
		}
		return LoginConstant.USER_LOGIN_SUCCESS;
	}

	@Override
	public int sysAdminLogin(User user,
			HttpServletRequest request, HttpServletResponse response) {
		if(user == null){
			return LoginConstant.LOGIN_FAILED;
		}
		String userPass = user.getPassWord();
		try {
			user = userService.getUserByUserName(user.getUserName());
		} catch (Exception e) {
			logger.error("系统管理员验证登录失败！" + e);
			return LoginConstant.LOGIN_FAILED;
		}
		if(user == null){
			return LoginConstant.LOGIN_FAILED_USER_NOT_EXIST;
		}
//		if(StringUtil.isNotBlank(user.getPassWord()) && !MD5.encodePassword(userPass, "MD5").equalsIgnoreCase(user.getPassWord())){
		if(StringUtil.isNotBlank(user.getPassWord()) && !userPass.equalsIgnoreCase(user.getPassWord())){
			return LoginConstant.LOGIN_FAILED_PASS_ERROR;
		}
		String sessionId = getSessionIdForUser(user);
		try {
			CookieUtil.setPageCookie(response, ConstantUtil.SESSION_ID_NAME, sessionId, 
					 "jack");
			CookieUtil.setPageCookie(response, ConstantUtil.USER_SESSION_ID_NAME, 
					String.valueOf(user.getId()), "jack");
		} catch (Exception e) {
			logger.error("验证系统管理员登录保存cookie出错！" + e);
		}
		request.setAttribute("user", user);
		return LoginConstant.USER_LOGIN_SUCCESS;
	}
	
	
	
	private String getSessionIdForUser(User user) {
		return MD5.encodePassword(user.getId() + "-" +
				ConstantUtil.USER_SESSION_ID_KEY + "-" + user.getPassWord(), "MD5");
	}

	@Override
	public boolean isSellerLogined(HttpServletRequest request) {
		String sessionId = CookieUtil.getCookieByDomain(request, RateConstant.SESSION_ID_NAME, RateConstant.WORKSMAP_CENTER_DOMAIN);
		if (sessionId == null) {
			return false;
		}
		String taobao_user_id = CookieUtil.getCookieByDomain(request, RateConstant.SELLER_SESSION_ID_NAME, RateConstant.WORKSMAP_CENTER_DOMAIN);
		if (StringUtil.isEmpty(taobao_user_id)) {
			return false;
		}
		
		TaoBaoSeller seller = userService.getSellerById(taobao_user_id);
		if(seller == null){
			return false;
		}
		String validSessionId = cookieService.getSessionIdForSeller(seller);
		if (!sessionId.equalsIgnoreCase(validSessionId)) {
			return false;
		}
		return true;
	}
}
